/**
    Copyright (c) 2010 yakiimo02
    Distributed under the New BSD License.
    See included license.txt or http://www.yakiimo3d.com/NewBSDLicense.txt
**/

#include "DXUT.h"
#include "SmallPtMgr.h"

SmallPtMgr    g_smallPtMgr;

/**
*/
SmallPtMgr::SmallPtMgr() : m_mode( SMALLPT_MODE_CPU_OPT )
{
    memset( &m_backBufferDesc, 0, sizeof( DXGI_SURFACE_DESC ) );
}

/**
*/
SmallPtMgr::~SmallPtMgr()
{
}

/**
*/
HRESULT SmallPtMgr::OnCreateDevice( ID3D11Device* pd3dDevice )
{
    return S_OK;
}

/**
*/
HRESULT SmallPtMgr::OnResizedSwapChain( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, bool bForceRecreate )
{
    HRESULT hr = S_OK;
    
        // First call.
    if( m_backBufferDesc.Width == 0 ||
        // Back buffer size has changed.
        ( pBackBufferSurfaceDesc->Width != m_backBufferDesc.Width || pBackBufferSurfaceDesc->Height != m_backBufferDesc.Height ) ||
        bForceRecreate        
        )
    {
        // recreate databuffer to match screen back buffer dimensions
        V_RETURN( m_dataBufferDX11.OnResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );

        m_cpu.Destroy();
        m_cpu.Create( &m_dataBufferDX11 );

        m_cpuMT.Destroy();
        m_cpuMT.Create( &m_dataBufferDX11 );
    }

    m_backBufferDesc = *pBackBufferSurfaceDesc;

    return S_OK;
}

/**
*/
void SmallPtMgr::OnFrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext,
                      double fTime, float fElapsedTime )
{
    if( m_mode == SMALLPT_MODE_CPU_OPT ) {
        m_cpuMT.Render( pd3dDevice, pd3dImmediateContext, &m_dataBufferDX11 );
    }
    else if( m_mode == SMALLPT_MODE_CPU_REF ) {
        m_cpu.Render( pd3dDevice, pd3dImmediateContext, &m_dataBufferDX11 );
    }
    else {
        assert( 0 );
    }
}

/**
*/
void SmallPtMgr::OnDestroyDevice()
{
    m_cpu.Destroy();
    m_cpuMT.Destroy();
    m_dataBufferDX11.Destroy();
}